const http = require('http');
const fs = require('fs');
const path = require('path');

// 指定要提供服务的目录
const publicDirectory = path.join(__dirname, 'public');

const server = http.createServer((req, res) => {
    // 构建请求的文件路径
    let filePath = path.join(publicDirectory, req.url === '/' ? 'index.html' : req.url);

    // 检查文件是否存在
    fs.access(filePath, fs.constants.F_OK, (err) => {
        if (err) {
            // 文件不存在，返回 404 错误
            res.statusCode = 404;
            res.end('404 Not Found');
            return;
        }

        // 获取文件扩展名以设置正确的 MIME 类型
        const extname = path.extname(filePath);
        let contentType = 'text/html';
        switch (extname) {
            case '.js':
                contentType = 'text/javascript';
                break;
            case '.css':
                contentType = 'text/css';
                break;
            case '.json':
                contentType = 'application/json';
                break;
            case '.png':
                contentType = 'image/png';
                break;
            case '.jpg':
            case '.jpeg':
                contentType = 'image/jpeg';
                break;
        }

        // 读取文件并返回给客户端
        fs.readFile(filePath, (err, data) => {
            if (err) {
                // 读取文件出错，返回 500 错误
                res.statusCode = 500;
                res.end('500 Internal Server Error');
            } else {
                // 设置响应头和状态码
                res.setHeader('Content-Type', contentType);
                res.statusCode = 200;
                res.end(data);
            }
        });
    });
});

const port = 3000;
server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});    